/*
  OA 里合同审批通过回写状态 及 产品线相关信息

*/
@RestResource(urlMapping='/CRM/upsertContractREST/*')
global  class UpsertContractREST {

    @HttpPost
    global static RestReturnMessage UpsertContractREST(String contract ,String details ) {

    	RestReturnMessage message = null;

    	

    	try{
            System.debug(contract);
    		if(contract == null || contract == '' )throw new DmlException('参数异常!'); 
            contract = contract.replaceAll('%0D%3Cbr%3E', '');//去掉换行符
            contract = contract.replaceAll('%0D', '');
            contract = contract.replaceAll('%09', '');
    		Map<String,Object> contractMap  = (Map<String,Object> )JSON.deserializeUntyped(EncodingUtil.urlDecode(contract,'UTF-8')) ; 
    		
    		if(!contractMap.containsKey('Id'))throw new DmlException('合同Id必传!');

    		//现代理产品/主推品牌及年度销售额
    		//DealerManageProduct__c 
    		Contract__c ct  = [select Id,Account__c , Account__r.RecordType.DeveloperName  from Contract__c where Id =:String.valueOf(contractMap.get('Id')) ];
    			//验证子表
    		//if(ct.Account__r.RecordType.DeveloperName == 'Dealer' && details == null )throw new DmlException('子表数据必传!');
    		List<Object> detailList = new List<Object>();
            
            if(details != null ) details = details.replaceAll('%0D%3Cbr%3E', '');
            if(details != null ) details = details.replaceAll('%0D', '');
            if(details != null && String.isBlank(details) == false ) detailList = (List<Object>)JSON.deserializeUntyped(EncodingUtil.urlDecode(details,'UTF-8')) ; 
            

    		//if(ct.Account__r.RecordType.DeveloperName == 'Dealer' && detailList.size() == 0  )throw new DmlException('子表数据必传!');
    		
    		Map<String,String> fieldsMap = new Map<String,String>();

    		//合同的所有字段
        	for(Schema.SObjectField f :Contract__c.SObjectType.getDescribe().fields.getMap().values()){

        		fieldsMap.put(f.getDescribe().getName().toUpperCase(), f.getDescribe().getType()+'');
        	}

        	//合同
		    SObject con = Contract__c.SObjectType.newSobject();



    		for(String k : contractMap.keySet()){

                String  tempk =  k.trim();
                if(String.isBlank(tempk)) continue;
    			  tempk =  tempk.toUpperCase();
 		       	con.put(k.trim(),UpsertObjectREST.dataHandler(contractMap.get(k) ,fieldsMap.get(tempk)));

    		}

    		///现代理产品/主推品牌及年度销售额
    		/*

				[{
	
					brand:'代理品牌',
					productLine:'代理产品线',
					area:'代理区域',
					grade:'代理等级'
				}]
    		*/
    		
    		List<MaccuraAuthorization__c> dmpList =new List<MaccuraAuthorization__c>();


    			//Map<String,String> brandMap = new Map<String,String>();
    			Set<String> productLineSet = new Set<String>();
                Set<String> brandSet = new Set<String>();
    			//1.处理品牌
    			for(Object o : detailList){

    				Map<String,Object> mo = (Map<String,Object>) o;
    				
    				if(mo.get('brand') == null )throw new DmlException('品牌不能为空!');
    				if(mo.get('brand') != null )brandSet.add(String.valueOf(mo.get('brand')).trim());

    				productLineSet.add(String.valueOf(mo.get('productLine')).trim());
    			}

    			//匹配品牌
                // if(detailList.size() > 0){

                //     List<Brand__c> blist = [select Id ,Name from Brand__c where Name in: brandMap.keySet()];
                //     if(blist.size() == 0)throw new DmlException('品牌:'+String.join(new List<String>(brandMap.keySet()), ',')+';不存在!');
                //     for(Brand__c b :blist){
                //         if(brandMap.containsKey(b.Name)){
                //             brandMap.put(b.Name, b.Id);
                //         }else{
                //             throw new DmlException('品牌不存在!');
                //         }
                //     }

                // }
    			
    			//匹配已经存在的 现迈克公司授权区域及等级情况 
    			Map<String, Id >dmpMap = new Map<String,Id>();
    			for(MaccuraAuthorization__c dmp : [select Id ,ProductLine__c,MaccuraBrand__c  from  MaccuraAuthorization__c
    				where ProductLine__c in:productLineSet and MaccuraBrand__c in:brandSet  and  MaccuraDealer__c=:ct.Account__c  ]){

    				dmpMap.put(dmp.ProductLine__c+dmp.MaccuraBrand__c,dmp.Id );
    			}

    			//设置值
    			for(Object o : detailList){

    				Map<String,Object> mo = (Map<String,Object>) o;
    				//DealerManageProduct__c dmp = new DealerManageProduct__c();
                    MaccuraAuthorization__c mAuth = new MaccuraAuthorization__c();

    				mAuth.ProductLine__c = mo.get('productLine') == null ? null : String.valueOf(mo.get('productLine')).trim();
    				mAuth.MaccuraBrand__c =  String.valueOf(mo.get('brand')).trim();
    				mAuth.AgentArea__c =  mo.get('area') == null ? null : String.valueOf(mo.get('area')).trim();
    				mAuth.ProxyGrade__c =  mo.get('grade') == null ? null : String.valueOf(mo.get('grade')).trim();
                    mAuth.Year__c = mo.get('dlnd') == null ? null : String.valueOf(mo.get('dlnd')).trim();
                    if(dmpMap.containsKey(mAuth.ProductLine__c+mAuth.MaccuraBrand__c))mAuth.Id = dmpMap.get(mAuth.ProductLine__c+mAuth.MaccuraBrand__c);
                    if(mAuth.Id == null )mAuth.MaccuraDealer__c = ct.Account__c ;

    				dmpList.add(mAuth);
    			}

    			
    		SavePoint sp = Database.setSavepoint();
    		try{

    			update con;
                System.debug('Brand__c==>'+dmpList);
    			if(dmpList.size() > 0 ) upsert dmpList;

    			message = Utils.getRestReturnMessage(true,'更新成功!',new List<Map<String ,String>>());
 
    		}catch(Exception e){
    			Database.rollback(sp);
    			message = Utils.getRestReturnMessage(false,'数据保存失败:'+e.getMessage(),new List<Map<String ,String>>());

    		}

    	}catch(Exception e ){
    			message = Utils.getRestReturnMessage(false,'数据保存失败:'+e.getMessage(),new List<Map<String ,String>>());

    	}

    	return message;
        
    }

    private static void checkNull(Object o ,String msg ){
    	if(o == null || String.isBlank( String.valueOf(o)))throw new DmlException(msg );
    	
    }
}